<template>
	<div class="outlet-container">
		<!-- 排污口列表 -->
		<div v-for="(item, index) in outlets" :key="item.id || index" class="outlet-row">
			<div class="outlet-content">
				<div class="outlet-value">{{ item.outletName || `排污口${index + 1}` }}</div>
				<div class="outlet-ops">
					<van-icon name="delete-o" color="#E94E65" @click="deleteOutlet(item.id)" />
					<van-icon name="edit" color="#1B9ADE" @click="editOutlet(item)" />
				</div>
			</div>
		</div>

		<!-- 添加排污口按钮 -->
		<div class="add-outlet-icon" @click="addOutlet">
			<van-icon name="plus" size="30px" color="#0099FF" />
		</div>

		<!-- 排污口编辑弹窗 -->
		<van-popup
			v-model:show="showPopup"
			position="right"
			:style="{ height: '100%', width: '100%' }"
			closeable
			close-icon-position="top-right"
			@close="closePopup"
		>
			<div class="outlets-form">
				<div class="title-panel">设施维护</div>

				<van-form>
					<!-- 排扣类别 -->
					<FormItemRadio
						v-model="formData.outletCategory"
						item-key="outletCategory"
						label="排扣类别"
						:required="true"
						:dic-key="categoryDicKey"
						@change="onCategoryChange"
					/>

					<!-- 排扣编号 -->
					<van-field
						v-model="formData.outletCode"
						name="outletCode"
						label="排扣编号"
						placeholder="请输入"
						required
						:rules="[{ required: true, message: '请输入排扣编号' }]"
					/>

					<!-- 排扣名称 -->
					<van-field
						v-model="formData.outletName"
						name="outletName"
						label="排扣名称"
						placeholder="请输入"
						required
						:rules="[{ required: true, message: '请输入排扣名称' }]"
					/>

					<!-- 设施名称 -->
					<van-field
						v-model="formData.facilityName"
						name="facilityName"
						label="设施名称"
						placeholder="请输入"
						required
						:rules="[{ required: true, message: '请输入设施名称' }]"
					/>

					<!-- 是否在线监测 -->
					<van-field name="isOnlineMonitor" label="是否在线监测" required>
						<template #input>
							<van-radio-group v-model="formData.isOnlineMonitor" direction="horizontal">
								<van-radio name="1">是</van-radio>
								<van-radio name="0">否</van-radio>
							</van-radio-group>
						</template>
					</van-field>

					<!-- 是否接管 (仅废水) -->
					<van-field v-if="pollutionType === 'FS'" name="outType" label="是否接管" required>
						<template #input>
							<van-radio-group v-model="formData.outType" direction="horizontal">
								<van-radio name="1">是</van-radio>
								<van-radio name="0">否</van-radio>
							</van-radio-group>
						</template>
					</van-field>

					<!-- 污水处理厂名称 -->
					<van-field
						v-if="formData.outType === '1'"
						v-model="formData.sewageName"
						name="sewageName"
						label="污水处理厂名称"
						placeholder="请输入"
						required
						:rules="[{ required: true, message: '请输入污水处理厂名称' }]"
					/>

					<!-- 排放河道名称 -->
					<van-field
						v-if="formData.outType === '0'"
						v-model="formData.riverName"
						name="riverName"
						label="排放河道名称"
						placeholder="请输入"
						required
						:rules="[{ required: true, message: '请输入排放河道名称' }]"
					/>

					<!-- 污染因子 -->
					<FormItemCheckbox
						v-model="formData.pollutionFactorCodeArr"
						item-key="pollutionFactorCodeArr"
						label="污染因子"
						:required="true"
						:dic-key="factorDicKey"
						@change="onFactorChange"
					/>

					<!-- 操作按钮 -->
					<div class="bot-btn-wrap">
						<van-row :gutter="20">
							<van-col :span="12">
								<van-button block type="primary" :loading="saving" :disabled="saving" @click.stop.prevent="handleSaveClick">
									{{ saving ? '保存中...' : '确定' }}
								</van-button>
							</van-col>
							<van-col :span="12">
								<van-button block plain type="primary" @click.stop="closePopup" :disabled="saving">返回</van-button>
							</van-col>
						</van-row>
					</div>
				</van-form>
			</div>
		</van-popup>
	</div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { getDic } from '../../api/index'
import { generateId } from '../../view/company/constants'
import Schema from 'async-validator'
import FormItemRadio from '../form-item-radio'
import FormItemCheckbox from '../form-item-checkbox'

export default {
	name: 'Outlet',
	components: {
		FormItemRadio,
		FormItemCheckbox,
	},
	props: {
		pollutionType: {
			type: String,
			default: 'FS', // FS: 废水, FQ: 废气
		},
		modelValue: {
			type: Array,
			default: () => [],
		},
	},
	emits: ['update:modelValue', 'change'],
	setup(props, { emit }) {
		// 响应式数据
		const outlets = ref([...props.modelValue])
		const showPopup = ref(false)
		const saving = ref(false) // 保存中状态，防止重复提交

		// 表单数据
		const formData = reactive({
			id: '',
			outletCategory: '',
			outletCode: '',
			outletName: '',
			facilityName: '',
			isOnlineMonitor: '',
			outType: '',
			sewageName: '',
			riverName: '',
			pollutionFactorCodeArr: [],
			pollutionType: props.pollutionType,
		})

		// 当前编辑的排污口ID
		const editingId = ref('')

		// 计算字典key
		const categoryDicKey = computed(() => {
			return props.pollutionType === 'FQ' ? 'ZQT_FQPKLX' : 'ZQT_FSPKLX'
		})

		const factorDicKey = computed(() => {
			return props.pollutionType === 'FQ' ? 'ZQT_FQWRYZ' : 'ZQT_FSWRYZ'
		})

		// 监听 props 变化（仅在父组件主动更新时同步）
		watch(
			() => props.modelValue,
			(newVal) => {
				console.log('父组件更新了modelValue，同步到本地')
				outlets.value = [...newVal]
			},
			{ deep: true }
		)

		// ❌ 移除自动watch emit，避免每次数据变化都触发父组件更新导致页面卡死
		// 改为在保存成功后手动emit一次

		// 手动通知父组件数据已更新
		const notifyParent = () => {
			console.log('手动通知父组件数据已更新')
			emit('update:modelValue', outlets.value)
			emit('change', outlets.value)
		}

		// 重置表单
		const resetForm = () => {
			Object.assign(formData, {
				id: generateId(),
				outletCategory: '',
				outletCode: '',
				outletName: '',
				facilityName: '',
				isOnlineMonitor: '',
				outType: '',
				sewageName: '',
				riverName: '',
				pollutionFactorCodeArr: [],
				pollutionType: props.pollutionType,
			})
			editingId.value = ''
		}

		// 添加排污口
		const addOutlet = () => {
			resetForm()
			showPopup.value = true
		}

		// 编辑排污口
		const editOutlet = (outlet) => {
			console.log('开始编辑排污口:', outlet.id, outlet)
			Object.assign(formData, {
				...outlet,
				// 确保污染因子数组格式正确
				pollutionFactorCodeArr: Array.isArray(outlet.pollutionFactorCodeArr)
					? outlet.pollutionFactorCodeArr
					: outlet.pollutionFactorCodeArr
					? [outlet.pollutionFactorCodeArr]
					: [],
			})
			editingId.value = outlet.id
			console.log('设置editingId为:', editingId.value)
			console.log('设置后的formData:', {
				id: formData.id,
				outletName: formData.outletName,
				outletCode: formData.outletCode,
			})
			showPopup.value = true
		}

		// 删除排污口
		const deleteOutlet = async (id) => {
			try {
				await showConfirmDialog({
					title: '确认删除',
					message: '确定要删除这个排污口吗？',
				})

				console.log('删除排污口, id:', id)
				outlets.value = outlets.value.filter((item) => item.id !== id)
				console.log('删除成功，通知父组件')

				// 手动通知父组件数据已更新
				notifyParent()

				showToast('删除成功')
			} catch (error) {
				// 用户取消删除
				console.log('用户取消删除')
			}
		}

		// 标志位：是否正在保存（避免关闭弹窗时重置数据）
		const isSaving = ref(false)

		// 关闭弹窗
		const closePopup = () => {
			console.log('closePopup被调用, isSaving:', isSaving.value)
			showPopup.value = false
			// 只有在非保存状态下才重置表单（避免保存时被重置）
			if (!isSaving.value) {
				console.log('非保存状态，重置表单')
				resetForm()
			} else {
				console.log('保存状态，不重置表单')
			}
		}

		// 排扣类别变化处理
		const onCategoryChange = ({ outletCategory }) => {
			console.log('排扣类别变化:', outletCategory)
			formData.outletCategory = outletCategory
			console.log('设置后的formData.outletCategory:', formData.outletCategory)
		}

		// 污染因子变化处理
		const onFactorChange = ({ pollutionFactorCodeArr }) => {
			console.log('污染因子变化:', pollutionFactorCodeArr)
			formData.pollutionFactorCodeArr = pollutionFactorCodeArr
			console.log('设置后的formData.pollutionFactorCodeArr:', formData.pollutionFactorCodeArr)
		}

		// 表单验证
		const validateForm = () => {
			const rules = {
				outletCategory: {
					type: 'string',
					required: true,
					message: '请选择排扣类别',
				},
				outletCode: {
					type: 'string',
					required: true,
					message: '请输入排扣编号',
				},
				outletName: {
					type: 'string',
					required: true,
					message: '请输入排扣名称',
				},
				facilityName: {
					type: 'string',
					required: true,
					message: '请输入设施名称',
				},
				isOnlineMonitor: {
					type: 'string',
					required: true,
					message: '请选择是否在线监测',
				},
				pollutionFactorCodeArr: {
					type: 'array',
					required: true,
					message: '请选择污染因子',
				},
			}

			// 废水特有的验证规则
			if (props.pollutionType === 'FS') {
				rules.outType = {
					type: 'string',
					required: true,
					message: '请选择是否接管',
				}

				if (formData.outType === '1') {
					rules.sewageName = {
						type: 'string',
						required: true,
						message: '请输入污水处理厂名称',
					}
				} else if (formData.outType === '0') {
					rules.riverName = {
						type: 'string',
						required: true,
						message: '请输入排放河道名称',
					}
				}
			}

			return new Promise((resolve, reject) => {
				const validator = new Schema(rules)
				validator.validate(formData, (errors, fields) => {
					if (errors) {
						showToast(errors[0].message)
						reject(errors)
					} else {
						resolve(formData)
					}
				})
			})
		}

		// 处理保存按钮点击（添加防抖和事件处理）
		const handleSaveClick = (event) => {
			console.log('=== 按钮被点击 ===')
			console.log('事件对象:', event)
			console.log('当前saving状态:', saving.value)

			// 阻止事件冒泡和默认行为
			if (event) {
				event.stopPropagation()
				event.preventDefault()
			}

			// 调用保存方法
			saveOutlet()
		}

		// 保存排污口
		const saveOutlet = () => {
			console.log('=== 开始保存排污口 ===')
			console.log('当前saving状态:', saving.value)

			// 防止重复提交
			if (saving.value) {
				console.log('正在保存中，请勿重复提交')
				return Promise.resolve()
			}

			// 设置保存状态
			saving.value = true
			console.log('设置saving为true')

			console.log('开始验证表单...')
			console.log('保存前的formData:', {
				id: formData.id,
				outletCategory: formData.outletCategory,
				outletCode: formData.outletCode,
				outletName: formData.outletName,
				facilityName: formData.facilityName,
				isOnlineMonitor: formData.isOnlineMonitor,
				outType: formData.outType,
				sewageName: formData.sewageName,
				riverName: formData.riverName,
				pollutionFactorCodeArr: formData.pollutionFactorCodeArr,
			})

			// 表单验证
			return validateForm()
				.then(() => {
					console.log('表单验证通过')
					console.log('保存时的editingId:', editingId.value)

					// 深拷贝表单数据
					const outletData = {
						id: formData.id,
						outletCategory: formData.outletCategory,
						outletCode: formData.outletCode,
						outletName: formData.outletName,
						facilityName: formData.facilityName,
						isOnlineMonitor: formData.isOnlineMonitor,
						outType: formData.outType,
						sewageName: formData.sewageName,
						riverName: formData.riverName,
						pollutionFactorCodeArr: [...formData.pollutionFactorCodeArr],
						pollutionType: formData.pollutionType,
					}

					console.log('outletData:', {
						id: outletData.id,
						outletName: outletData.outletName,
						outletCode: outletData.outletCode,
					})

					console.log('准备更新数据，先关闭弹窗')

					// 保存当前的editingId，避免异步执行时被重置
					const currentEditingId = editingId.value
					const isEditing = !!currentEditingId
					console.log('当前操作:', isEditing ? '编辑' : '新增', 'editingId:', currentEditingId)
					console.log('outletData.id:', outletData.id, '与currentEditingId是否相等:', outletData.id === currentEditingId)

					// 设置保存标志，防止closePopup重置数据
					isSaving.value = true
					console.log('设置isSaving为true')

					// 先关闭弹窗（在更新数据之前，避免watch触发时弹窗还在）
					showPopup.value = false

					// 使用 setTimeout 确保弹窗关闭后再更新数据
					console.log('延迟更新数据')
					setTimeout(() => {
						try {
							console.log('开始更新outlets数据, 是否编辑:', isEditing)
							if (isEditing) {
								// 更新现有排污口
								const index = outlets.value.findIndex((item) => item.id === currentEditingId)
								if (index > -1) {
									outlets.value.splice(index, 1, outletData)
									console.log('更新排污口成功, index:', index, 'id:', currentEditingId)
								} else {
									console.error('未找到要更新的排污口, editingId:', currentEditingId)
								}
							} else {
								// 添加新排污口
								outlets.value.push(outletData)
								console.log('添加排污口成功, 当前总数:', outlets.value.length)
							}

							console.log('数据更新完成，通知父组件')
							// 手动通知父组件数据已更新
							notifyParent()

							console.log('显示成功提示')
							showToast('保存成功')

							console.log('重置表单')
							resetForm()

							console.log('重置isSaving标志')
							isSaving.value = false
						} catch (e) {
							console.error('更新数据或显示提示失败:', e)
						} finally {
							console.log('重置saving状态')
							saving.value = false
							console.log('=== 保存完成 ===')
						}
					}, 100)
				})
				.catch((error) => {
					console.error('=== 保存失败 ===')
					console.error('错误详情:', error)
					console.error('错误类型:', typeof error)
					console.error('是否为数组:', Array.isArray(error))

					// 验证失败或其他错误，确保重置saving状态
					saving.value = false
					isSaving.value = false
					console.log('重置saving和isSaving为false')

					// 如果是验证错误，错误信息已经在 validateForm 中显示了
					if (!error || !Array.isArray(error)) {
						// 非验证错误，显示通用错误信息
						console.log('显示通用错误提示')
						showToast('保存失败，请重试')
					} else {
						console.log('验证错误，已在validateForm中显示')
					}
				})
		}

		return {
			outlets,
			showPopup,
			formData,
			saving,
			categoryDicKey,
			factorDicKey,
			addOutlet,
			editOutlet,
			deleteOutlet,
			closePopup,
			onCategoryChange,
			onFactorChange,
			handleSaveClick,
			saveOutlet,
		}
	},
}
</script>

<style lang="less" scoped>
.outlet-container {
	padding: 0;
}

.outlet-row {
	border-bottom: 1px solid #f4f4f4;
}

.outlet-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 16px;
}

.outlet-value {
	flex: 1;
	font-size: 14px;
	color: #888;
}

.outlet-ops {
	display: flex;
	align-items: center;
	gap: 16px;
}

.add-outlet-icon {
	width: calc(100% - 32px);
	height: 40px;
	margin: 10px 16px;
	border: 1px dashed #ddd;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 4px;
	cursor: pointer;

	&:hover {
		border-color: #0099ff;
		background-color: #f0f8ff;
	}
}

.outlets-form {
	height: 100%;
	background-color: #f7f8fa;

	.title-panel {
		font-size: 18px;
		font-weight: 600;
		padding: 16px;
		background: white;
		border-bottom: 1px solid #ebedf0;
	}

	.bot-btn-wrap {
		padding: 20px;
		background: white;
		margin-top: 20px;
	}
}

:deep(.van-field__label) {
	width: 100px;
}

:deep(.van-radio-group) {
	.van-radio {
		margin-right: 20px;
	}
}
</style>
